<?php
// 本类由系统自动生成，仅供测试用途
class ControlTableAction extends CommonAction {
	function _filter(&$map) {
		$map['removed']=1;
		$userid=$_POST ['user'];
		$start=$_POST ['start'];
		$end=$_POST ['end'];
		$shipper=$_POST ['shipper'];
		$customer=$_POST ['customer'];
		$carstat=$_POST ['carstat'];
		$product=$_POST ['product'];
		
// 		if(!empty($userid)){
// 			$map ['userid'] = array ('like',"%" . $_POST ['user'] . "%" );
// 		}
// 		if(!empty($shipper)){
// 			$map['shipper'] = array('eq',$shipper);
// 		}
// 		if(!empty($customer)){
// 			$map['customer'] = array('eq',$customer);	
// 		}
// 		if(!empty($carstat)){
// 		    $map['carstat'] = array('eq',$carstat);
// 		}
// 		if(!empty($product)){
// 			$map['product'] = array('eq',$product);
// 		}
// 		if(!empty($start)||!empty($end)){
// 			$map['controldate']=array('between',array($start,$end));
// 		}
//   2013年5月3日需求变更，不在需要限制仅显示自己操作的记录
// 		if('1'!==$_SESSION [C ( 'USER_AUTH_KEY' )]){
// 			$map['operator']=$_SESSION [C ( 'USER_AUTH_KEY' )];
// 		}
	}
	public function _before_index() {
		$model = M ( "ControlTable" );
		$list = $model->select ();
		$model3 = M ( "Carrier" );
		$Carrier = $model3->select ();
		$model2 = M ( "Provider" );
		$Provider=$model2->select ();
		$model4 = M ( "Customer" );
		$Customer=$model4->select ();
		//按照controldate(调度时间升序)排序
		$_REQUEST['_order'] = 'controldate';
		$_REQUEST['_sort'] = 'desc';
		$this->assign ( 'carr', $Carrier );
		$this->assign ( 'provider', $Provider );
		$this->assign ( 'groupList', $list );
		$this->assign ( 'customer', $Customer );
	}
	public function read(){
		$id=$_REQUEST['id'];
		$model=M('ControlTable');
		$ControlTable=$model->where('id='.$id)->find();
		$model3 = M ( "Carrier" );
		$Carrier = $model3->select ();
		$model2 = M ( "Provider" );
		$Provider=$model2->select ();
		$model4 = M ( "Customer" );
		$Customer=$model4->select ();
		$this->assign ( 'customer', $Customer );
		$this->assign ( 'provider', $Provider );
		$this->assign('carr',$Carrier);
		$this->assign('vo',$ControlTable);
		$this->display();
	}
	public function _before_add() {
		/**
		 * 下拉框显示信息
		 */
		// $model1 = M ( "StoreManage" );
		// $ShortMessage = $model1->select ();
        $id=$_REQUEST['id'];
		$model2 = M ( "Provider" );
		$model1 = M('ContractLog');
		$model4 = M ( "Customer" );
		if (!empty($id)){
			$Conlog = $model1->find($id);
			//如果是客户合同的拟定调度，则带回客户的值.否则带回供应商的信息
			if($Conlog['type']==1){
				$this->assign('customer',$Conlog['secondname']);
				$this->assign('customerid',$Conlog['secondid']);
				$this->assign('type',1);
			}else{
				if($Conlog['type']==2){
					$this->assign('provider',$Conlog['secondname']);
					$this->assign('providerid',$Conlog['secondid']);
					$this->assign('type',2);
				}
			}
			//当该拟定调度payondelivery值为1时，关于改拟定调度信息生成的调度提示为款到卸车
			if($Conlog['payondelivery']==1){
				$this->assign('payondelivery',1);
			}
			$this->assign('product',$Conlog['goodname']);
		}
		$Psql = "select * from mlt_contract_log where status<100 and status>=0 and type = 2";
		$Provider = $model2->query($Psql);
		// 客户信息
		$Csql = "select * from mlt_contract_log where status<100 and status>=0 and type = 1";
		$Customer = $model4->query($Csql);
		//$Customer = $model4->where('removed!=2')->select ();
		$model3 = M ( "Carrier" );
		$Carrier = $model3->select ();
		// //获得子公司的信息
		$this->getSubCompany ();
		// 获得商品信息
		$this->getGoods ();
		/*
		 * $model4 = M ( "Car" ); $Car = $model4->where ( 'status=1' )->select
		 * ();
		 */
	
		
		$model = M ( "ControlTable" );
		$list = $model->select ();
		$this->assign ( 'list', $list );
		// $this->assign ( 'list1', $ShortMessage );
		$this->assign ( 'list2', $Provider );
		$this->assign ( 'list3', $Carrier );
		$this->assign ( 'list4', $Customer );
		/* $this->assign ( 'list4', $Car ); */
		$userModel = M ( 'User' );
		$user = $userModel->query('SELECT  *  FROM  `mlt_user` ORDER BY CONVERT( fullname USING gbk ) COLLATE gbk_chinese_ci ASC;');
		$this->assign ( 'user', $user );
		$freightModel = M ( 'Freight' );
		$freight = $freightModel->distinct ( true )->field ( 'startaddress' )->select ();
		$end = $freightModel->distinct ( true )->field ( 'endaddress' )->select ();
		$this->assign ( 'freight', $freight );
		$this->assign ( 'end', $end );
		$this->assign('contractlogid',$id);
	}
	function add(){
		$ajax = $_REQUEST['ajax'];
		if($ajax=='a'){
			$this->customerajax();
		}else{
			$this->display("add");
		}
	}
	
	function editton() {
		if("true"==$_REQUEST['updateton']){
			$this->updateton();
		}else{
			$model = M ( 'ControlTable' );
			$id = $_REQUEST ['id'];
			$vo = $model->getById ( $id );
			if(($vo['Factorynetweight']!==null&&$vo['Factorynetweight']!=='0')||($vo['sweight']!==null&&$vo['sweight']!=="0")||($vo['eweight']!==null&&$vo['eweight']!=="0")){
				$this->ajaxReturn(0,'已输入吨数信息，不可更改!',300);
			}else{
					$this->assign ( 'vo', $vo );
					$this->display ();
			}
		}
	}
	public function _before_edit() {
		$id=$_REQUEST['id'];
		$model=M('ControlTable');
		$model1=M('ContractLog');
		$Con=$model->where('id='.$id)->find();
		$model3 = M ( "Carrier" );
		$Carrier = $model3->select ();
		$model2 = M ( "Provider" );
		$Provider=$model2->select ();
// 		$model4 = M ( "Customer" );
// 		$Customer=$model4->select ();
		$model5 = M ( "Car" );
		$Car = $model5->select ();
		$model6 = M ( "Customer" );
		$sql6 = " select * from mlt_customer where id in( select secondid from mlt_contract_log where type = 1 and status>=0 and status<100) or id in(1,2,3)";
		//$Customer=$model6->query($sql6);
		$Customer = $model1->where('type = 1 and status>=0  and goodname = \''.$Con['product'].'\'')->select();
		$userModel = M ( 'User' );
		$user = $userModel->select ();
		$this->assign ( 'customer', $Customer );
		$this->assign ( 'provider', $Provider );
		$this->assign('carr',$Carrier);
		$this->assign('vo',$Con);
		// //获得子公司的信息
		$this->getSubCompany ();
		// 获得商品信息
		$this->getGoods ();
		$this->assign ( 'list4', $Car );
		$this->assign ( 'user', $user );
		$freightModel = M ( 'Freight' );
		$freight = $freightModel->distinct ( true )->field ( 'startaddress' )->select ();
		$end = $freightModel->distinct ( true )->field ( 'endaddress' )->select ();
		$this->assign('userkey',$_SESSION [C ( 'USER_AUTH_KEY' )]);
		$this->assign ( 'freight', $freight );
		$this->assign ( 'end', $end );
	}
	
	// 获得子公司的信息
	public function getSubCompany() {
		$Company = M ( 'Company' );
		$subcompany = $Company->select ();
		$this->assign ( 'subcompany', $subcompany );
	}
	// 获得商品信息
	public function getGoods() {
		$Goods = M ( 'Goods' );
		$goodslist = $Goods->select ();
		$this->assign ( 'goods', $goodslist );
	}
	public function _before_insert() {
	    //$customerid = $_REQUEST ['customer']; // 客户
		$destination = $_REQUEST ['destination']; // 目的地
		$product = $_REQUEST ['product']; // 产品名称
		$start = $_REQUEST ['start']; // 起始地
		$type = $_REQUEST['type'];
		//$providerid = $_REQUEST ['provider']; // 供应商
		if($type=='1'){
			$providerAndcontractlogid = explode(',', $_REQUEST['provider']);
			$providerid = $providerAndcontractlogid[1]; // 供应商
			$customerid = $_REQUEST ['customer']; // 客户
			$_POST['provider'] = $providerid;
			$_POST['contractlogid'] = $_REQUEST['contractlogid'];
			$_POST['tocontractlogid'] = $providerAndcontractlogid[0]; 
		}else{
			if($type=='2'){
				$customerAndcontractlogid = explode(',', $_REQUEST['customer']);
				$customerid = $customerAndcontractlogid [1]; // 客户
				$providerid = $_REQUEST ['provider']; // 供应商
				$_POST['customer'] = $customerid;
				$_POST['contractlogid'] = $customerAndcontractlogid[0];
				$_POST['tocontractlogid'] = $_REQUEST['contractlogid'];
			}
		}
		//拟定调度表的ID
		$contractlogid = $_REQUEST['contractlogid'];
		$model1 = M('ContractLog');
		$model2 = M ( "Provider" );
		$model3 = M ( "StoreManage" );
		$model4 = M ( "Customer" );
		$model5 = M('CustomerGood');
		if ($customerid){
			$customers=$model4->where('id='.$customerid)->find();
			$customer=$customers['customername'];
			$map['customerid']=$customerid;
		}else{
			$map['customerid']=null;
			$customer=null;
		}
		if($providerid){
			$provider = $model2->where('id='.$providerid)->find();
			$providername = $provider['providername'];
		}else{
			$providername=null;
		}
		
		
    	$map['goodname']=$product;
		$cusgood = $model5->where($map)->select();
		
		//判断仓库之间，起始地目的地之间是否相同
		$storenameA='storeA';
		$storenameB='storeB';
		$storenameC='storeC';
	    if($customer=="东明库"){
	    	if($providername=="东明库"){
	    		$this->ajaxReturn(0,'客户与供应商不能同时为东明库！',300);
	    	}else{
	    		if($start=="东明库"){
	    			$this->ajaxReturn(0,'客户与起始地不能同时为东明库！',300);
	    		}else{
	    			if($destination!=="东明库"){
	    				$this->ajaxReturn(0,'客户为东明库时目的地必须为东明库！',300);
	    			}
	    		}
	    	}
	    }
	    if($customer=="南曹库"){
	    	if($providername=="南曹库"){
	    		$this->ajaxReturn(0,'客户与供应商不能同时为南曹库！',300);
	    	}else{
	    		if($start=="南曹库"){
	    			$this->ajaxReturn(0,'客户与起始地不能同时为南曹库！',300);
	    		}else{
	    			if($destination!=="南曹库"){
	    				$this->ajaxReturn(0,'客户为南曹库时目的地必须为南曹库！',300);
	    			}
	    		}
	    	}
	    }
	    if($customer=="金海库"){
	    	if($providername=="金海库"){
	    		$this->ajaxReturn(0,'客户与供应商不能同时为金海库！',300);
	    	}else{
	    		if($start=="金海库"){
	    			$this->ajaxReturn(0,'客户与起始地不能同时为金海库！',300);
	    		}else{
	    			if($destination!=="金海库"){
	    				$this->ajaxReturn(0,'客户为金海库时目的地必须为金海库！',300);
	    			}
	    		}
	    	}
	    }
	    if($providername=="东明库"){
	    	if($destination=="东明库"){
	    		$this->ajaxReturn(0,'供应商与目的地不能同时为东明库！',300);
	    	}else{
	    		if($start!=="东明库"){
	    			$this->ajaxReturn(0,'供应商为东明库时起始地必须为东明库！',300);
	    		}
	    	}
	    }
	  if($providername=="南曹库"){
	    	if($destination=="南曹库"){
	    		$this->ajaxReturn(0,'供应商与目的地不能同时为南曹库！',300);
	    	}else{
	    		if($start!=="南曹库"){
	    			$this->ajaxReturn(0,'供应商为南曹库时起始地必须为南曹库！',300);
	    		}
	    	}
	    }
	  if($providername=="金海库"){
	    	if($destination!=="金海库"){
	    		$this->ajaxReturn(0,'供应商与目的地不能同时为金海库！',300);
	    	}else{
	    		if($start=="金海库"){
	    			$this->ajaxReturn(0,'供应商为金海库时起始地必须为金海库！',300);
	    		}
	    	}
	    }
	    if($destination=="东明库"){
	    	if($customer!=="东明库"){
	    		$this->ajaxReturn(0,'目的地为东明库时客户必须为东明库！',300);
	    	}
	    }
	    if($destination=="南曹库"){
	    	if($customer!=="南曹库"){
	    		$this->ajaxReturn(0,'目的地为南曹库时客户必须为南曹库！',300);
	    	}
	    }
	    if($destination=="金海库"){
	    	if($customer!=="金海库"){
	    		$this->ajaxReturn(0,'目的地为金海库时客户必须为金海库！',300);
	    	}
	    }
	    if($start=="东明库"){
	    	if($providername!=="东明库"){
	    		$this->ajaxReturn(0,'起始地为东明库时供应商必须为东明库！',300);
	    	}
	    }
	    if($start=="南曹库"){
	    	if($providername!=="南曹库"){
	    		$this->ajaxReturn(0,'起始地为南曹库时供应商必须为南曹库！',300);
	    	}
	    }
	    if($start=="金海库"){
	    	if($providername!=="金海库"){
	    		$this->ajaxReturn(0,'起始地为金海库时供应商必须为金海库！',300);
	    	}
	    }
	    if($start==$destination){
	    	$this->ajaxReturn(0,'起始地目的地不能相同！',300);
	    }
	    
	    //判断仓库是否存在相关商品
		if ($customer == "东明库" ||$destination=="东明库"||$start == "东明库" || $providername == "东明库") {
			$d = $model3->where('storename=\''.$storenameA.'\''.' and product=\''.$product.'\'')->select();
			if (! $d) {
				$this->ajaxReturn ( '0', '东明库列表不存在' . $product . '相关物品!', '300' );
			}
		}
		if ($customer == "南曹库" ||$destination=="南曹库"||$start == "南曹库" || $providername == "南曹库") {
			$n = $model3->where('storename=\''.$storenameB.'\''.' and product=\''.$product.'\'')->select();
			if (! $n) {
				$this->ajaxReturn ( '0', '南曹库列表不存在' . $product . '相关物品!', '300' );
			}
		}
		if ($customer == "金海库" ||$destination=="金海库"||$start == "金海库" || $providername == "金海库") {
			$j = $model3->where('storename=\''.$storenameC.'\''.' and product=\''.$product.'\'')->select();
			if (! $j) {
				$this->ajaxReturn ( '0', '金海库列表不存在' . $product . '相关物品!', '300' );
			}
		}
		//判断客户是否存在该商品
		if($customer!=="金海库"&&$customer!=="东明库"&&$customer!=="南曹库"){
			$model6 = M('CustomerGood');
			$cusgood=$model6->where('customerid='.$customerid)->select();
			$tru=false;
			for($i=0;$i<count($cusgood);$i++){
				if($cusgood[$i]['product']==$product){
					$tru=true;
				}
			}
			if(!$tru){
				$this->ajaxReturn(0,'本客户不存在'.$product.'物品！',300);
			}
		}
		
		//客户未供货量不足30吨是不允发货
// 		if($cusgood[0]['nosupply']<30&&($customer!=="东明库" && $customer!=="南曹库")){
// 			$this->ajaxReturn ( '0', '客户未供货量不足以发货！', '300' );
// 		}
		//当拟定调度的payondelivery值为1时关于该信息的调度payondelivery值也为1（款到卸车）
		$conlog = $model1->find($contractlogid);
		if($conlog['payondelivery']==1){
			$_POST['payondelivery']=1;
		}else{
			$_POST['payondelivery']=0;
		}
	}
	
	//26日更新前 吨数录入 之后需要删除
	public function oldupdateton() {
		$id=$_REQUEST['id'];
		$carstat=$_REQUEST['carstat'];
		$sweight=bcsub($_REQUEST['eweight'],$_REQUEST['sweight'],4);// 出厂净重=毛重-皮重
		$model = M ( 'Provider' );
		$model->startTrans();
		$result=true;
		$result1 = true;
		$RSMDM = true;
		$RSMNC = true;
		$RSMJH = true;
		$model3 = M ( "StoreManage" );
		$model4 = M('ControlTable');
		$ControlTable=$model4->where('id='.$id)->find();
		$providername = $ControlTable['provider'];//供应商
		$shipper = $ControlTable['shipper']; // 发货方
		$customer = $ControlTable['customer']; // 客户
		$product = $ControlTable['product']; // 产品名称
		$start = $ControlTable['start']; // 起始地
		$destination = $ControlTable['destination']; // 目的地
		$carrier = $ControlTable['carrier']; // 承运方
		$carno = $ControlTable['carno']; // 车牌号
		$orders = $ControlTable['orders']; // 订单号
		// 修改供应商供应表信息
		$Provider = $model->where ( 'id=\'' . $providername . '\'' )->find ();
		if (""==$providername||($Provider['providername']=="南曹库")||($Provider['providername']=="东明库")||($Provider['providername']=="金海库")) {
			$storenameA='storeA';
			$storenameB='storeB';
			$storenameC='storeC';
			// 当起始地或供应商选择为仓库时
			if ($start == "东明库") {
				if($destination=="东明库"){
					$model->rollback();
					$this->ajaxReturn ( '0', "起始地目的地不能同时为东明库！", '300' );
				}else{
					$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->select ();
					if ($Astoremanage) {
						$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
						if ($datage ['stock'] < 0) {
							$model->rollback();
							$this->ajaxReturn ( 0, '东明库存不足！', 300 );
						}else{
							$RSMDM = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->save($datage);
						}
					} else {
						$model->rollback();
						$this->ajaxReturn ( '0', '东明库列表不存在' . $product . '相关物品!', '300' );
					}
				}
			}
			if ($start == "南曹库") {
				if($destination == "南曹库"){
					$model->rollback();
					$this->ajaxReturn ( '0', "起始地目的地不能同时为南曹库！", '300' );
				}else{
					$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->select ();
					if ($Astoremanage) {
						$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
						if ($datage ['stock'] < 0) {
							$model->rollback();
							$this->ajaxReturn ( 0, '南曹库库存不足！', 300 );
						}else{
							$RSMNC = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->save($datage);
						}
					} else {
						$model->rollback();
						$this->ajaxReturn ( '0', '南曹库列表不存在' . $product . '相关物品!', '300' );
					}
				}
			}
			if ($start == "金海库") {
				if($destination == "金海库"){
					$model->rollback();
					$this->ajaxReturn ( '0', "起始地目的地不能同时为金海库！", '300' );
				}else{
					$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->select ();
					if ($Astoremanage) {
						$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
						if ($datage ['stock'] < 0) {
							$model->rollback();
							$this->ajaxReturn ( 0, '金海库库存不足！', 300 );
						}else{
							$RSMJH = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->save($datage);
						}
					} else {
						$model->rollback();
						$this->ajaxReturn ( '0', '金海库列表不存在' . $product . '相关物品!', '300' );
					}
				}
			}
		}else{
			if ($shipper == "普天") {
				$data ['wshipment1'] = bcsub($Provider ['wshipment1'],$sweight,4);
				$i = 1;
			} else {
				if ($shipper == "兰亭") {
					$data ['wshipment2'] = bcsub($Provider ['wshipment2'],$sweight,4);
					$i = 2;
				} else {
					if ($shipper == "天地") {
						$data ['wshipment3'] = bcsub($Provider ['wshipment3'],$sweight,4);
						$i = 3;
					}
				}
			}
			if ($data ['wshipment' . $i] < 0) {
				$model->rollback();
				$this->ajaxReturn ( '0', $shipper."对应的供应商无足够货物可用", '300' );
			} else {
				$result = $model->where ( 'id=\'' . $providername . '\'' )->save ( $data );
			}
		}
		// 增加租车信息
		if (""!==$ControlTable['carrier']) {
			$model1 = M ( 'CarrierDispatch' );
	
			$map ['carrierid'] = $carrier;
			$map ['sendername'] = $shipper;
			$map ['customer'] = $customer;
			$map ['providername'] = $providername;
			$map ['carno'] = $carno;
			$map ['beginning'] = $start;
			$map ['destination'] = $destination;
			$map ['cweight'] = $sweight;
			$map ['status'] = 0;
			$map ['orders'] = $orders;
				
			$result1 = $model1->add ( $map );
		}
		//当客户选项或目的地选择为:仓库 时
		if ($customer == "东明库" || $destination == "东明库") {
			$storemanagedata = $model3->where('storename=\''.$storenameA.'\'')->getByProduct ( $product );
			if (! $storemanagedata) {
				$model->rollback();
				$this->ajaxReturn ( '0', '东明库列表不存在' . $product . '相关物品!', '300' );
			}
		}
		//南曹库判断
		if ($customer == "南曹库" || $destination == "南曹库") {
			$storemanagedata = $model3->where('storename=\''.$storenameB.'\'')->getByProduct ( $product );
			if (! $storemanagedata) {
				$model->rollback();
				$this->ajaxReturn ( '0', '南曹库列表不存在' . $product . '相关物品!', '300' );
			}
		}
	
		//金海库判断
		if ($customer == "金海库" || $destination == "金海库") {
			$storemanagedata = $model3->where('storename=\''.$storenameC.'\'')->getByProduct ( $product );
			if (! $storemanagedata) {
				$model->rollback();
				$this->ajaxReturn ( '0', '金海库列表不存在' . $product . '相关物品!', '300' );
			}
		}
		$data4['id']=$_REQUEST['id'];
		$data4['sweight']=$_REQUEST['sweight'];//皮重
		$data4['eweight']=$_REQUEST['eweight'];//毛重
		$data4['Factorynetweight']=$sweight;//出厂净重
		$data4['carstat']=$_REQUEST['carstat'];
		$result4=$model4->save ($data4);
	
		//写入调度信息
		$model5=M('ControlLog');
		$n=$_SESSION['loginUserName'] ;//当前操作人
		$data['control']=$_REQUEST['id'];//对应的调度信息ID
		$data['logtime']=date('YmdHis');//用于调度进度显示的时间
		$data['log']='订单号为：'.$orders.'被'.$n.'录入吨数，毛重：'.$_REQUEST['eweight'].'皮重：'.$_REQUEST['sweight'];//用于调度进度显示的记录
		$result5=$model5->add($data);
		if (($result!==false) && ($result1!==false)&&($result4!==false) && ($result5!==false)&&($RSMDM!==false)&&($RSMJH!==false)&&($RSMNC!==false)) {
			$model->commit (); // 提交事务
			$this->ajaxReturn ( 1,'信息添加成功！', 200 );
		} else {
			$model->rollback ();
			$this->ajaxReturn ( 0, '数据库操作出错请联系管理员!', 300 );
		}
	}
	
	//吨数录入
	public function updateton() {
		
		$id=$_REQUEST['id'];
		$model1 = M ( 'CarrierDispatch' );
		$model2 = M('ContractLog');
		$carstat=$_REQUEST['carstat'];
		$sweight=bcsub($_REQUEST['eweight'],$_REQUEST['sweight'],4);// 出厂净重=毛重-皮重
		$model = M ( 'Provider' );
		//开启事务
		$model2->startTrans();
		$result=true;
		$result1 = true;
		$RSMDM = true;
		$RSMNC = true;
		$RSMJH = true;
		$model3 = M ( "StoreManage" );
		$model4 = M('ControlTable');
		$model5=M('ControlLog');
		$ControlTable=$model4->where('id='.$id)->find();
		$providername = $ControlTable['provider'];//供应商
		$shipper = $ControlTable['shipper']; // 发货方
		$customer = $ControlTable['customer']; // 客户
		$product = $ControlTable['product']; // 产品名称
		$start = $ControlTable['start']; // 起始地
		$destination = $ControlTable['destination']; // 目的地
		$carrier = $ControlTable['carrier']; // 承运方
		$carno = $ControlTable['carno']; // 车牌号
		$orders = $ControlTable['orders']; // 订单号
		//判断输入的吨数是否大于拟定调度要求的可调度吨数
		$ContractLog = $model2->find($ControlTable['contractlogid']);
		$toContractLog = $model2->find($ControlTable['tocontractlogid']);
		if(empty($ControlTable['contractlogid'])){
			$this->oldupdateton();
		}else{
		//拟定调度表可调度吨数
		$capacity = $ContractLog['capacity'];
		$tocapacity = $toContractLog['capacity'];
		//拟定调度表已调度吨数
		$alshipment = $ContractLog['alshipment'];
		$toalshipment = $toContractLog['alshipment'];
		//本次调度后已调度吨数
		$afteralshipment=bcadd($alshipment,$sweight,4);
		$toafteralshipment=bcadd($toalshipment,$sweight,4);
		
		
		
		
		
// 		if($sweight>(bcsub($capacity,$alshipment,4))){
// 			$this->ajaxReturn(0,'毛重-皮重（出场净重）大于可调度吨数，请确认！',300);
// 		}else{
// 			$datactlog['alshipment']=$afteralshipment;
// 			$datactlog['status'] = ($datactlog['alshipment']/$capacity)*100;
// 		}
		$datactlog['alshipment']=$afteralshipment;
		$datactlog['status'] = ($datactlog['alshipment']/$capacity)*100;
		
		$todatactlog['alshipment'] = $toafteralshipment;
		$todatactlog['status'] =($datactlog['alshipment']/$tocapacity)*100;
			
		// 修改供应商供应表信息
		$Provider = $model->where ( 'id=\'' . $providername . '\'' )->find ();
		if (""==$providername||($Provider['providername']=="南曹库")||($Provider['providername']=="东明库")||($Provider['providername']=="金海库")) {
			$storenameA='storeA';
			$storenameB='storeB';
			$storenameC='storeC';
			// 当起始地或供应商选择为仓库时
			if ($start == "东明库") {
				if($destination=="东明库"){
					$model2->rollback();
					$this->ajaxReturn ( '0', "起始地目的地不能同时为东明库！", '300' );
				}else{
					$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->select ();
					if ($Astoremanage) {
						$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
						if ($datage ['stock'] < 0) {
							$model2->rollback();
							$this->ajaxReturn ( 0, '东明库存不足！', 300 );
						}else{
							$RSMDM = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->save($datage);
						}
					} else {
						$model2->rollback();
						$this->ajaxReturn ( '0', '东明库列表不存在' . $product . '相关物品!', '300' );
					}
				}
			}
			if ($start == "南曹库") {
				if($destination == "南曹库"){
					$model2->rollback();
					$this->ajaxReturn ( '0', "起始地目的地不能同时为南曹库！", '300' );
				}else{
					$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->select ();
					if ($Astoremanage) {
						$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
						if ($datage ['stock'] < 0) {
							$model2->rollback();
							$this->ajaxReturn ( 0, '南曹库库存不足！', 300 );
						}else{
							$RSMNC = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->save($datage);
						}
					} else {
						$model2->rollback();
						$this->ajaxReturn ( '0', '南曹库列表不存在' . $product . '相关物品!', '300' );
					}
				}
			}
			if ($start == "金海库") {
				if($destination == "金海库"){
					$model2->rollback();
					$this->ajaxReturn ( '0', "起始地目的地不能同时为金海库！", '300' );
				}else{
					$Astoremanage = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->select ();
					if ($Astoremanage) {
						$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
						if ($datage ['stock'] < 0) {
							$model2->rollback();
							$this->ajaxReturn ( 0, '金海库库存不足！', 300 );
						}else{
							$RSMJH = $model3->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->save($datage);
						}
					} else {
						$model2->rollback();
						$this->ajaxReturn ( '0', '金海库列表不存在' . $product . '相关物品!', '300' );
					}
				}
			}
		}else{
			if ($shipper == "普天") {
				$data ['wshipment1'] = bcsub($Provider ['wshipment1'],$sweight,4);
				$i = 1;
			} else {
				if ($shipper == "兰亭") {
					$data ['wshipment2'] = bcsub($Provider ['wshipment2'],$sweight,4);
					$i = 2;
				} else {
					if ($shipper == "天地") {
						$data ['wshipment3'] = bcsub($Provider ['wshipment3'],$sweight,4);
						$i = 3;
					}
				}
			}
			if ($data ['wshipment' . $i] < 0) {
				$model2->rollback();
				$this->ajaxReturn ( '0', $shipper."对应的供应商无足够货物可用", '300' );
			} else {
				$result = $model->where ( 'id=\'' . $providername . '\'' )->save ( $data );
			}
		}
		// 增加租车信息
		if (""!==$ControlTable['carrier']) {
			$map ['carrierid'] = $carrier;
			$map ['sendername'] = $shipper;
			$map ['customer'] = $customer;
			$map ['providername'] = $providername;
			$map ['carno'] = $carno;
			$map ['beginning'] = $start;
			$map ['destination'] = $destination;
			$map ['cweight'] = $sweight;
			$map ['status'] = 0;
			$map ['orders'] = $orders;
			$result1 = $model1->add ( $map );
		}
	  //当客户选项或目的地选择为:仓库 时
		if ($customer == "东明库" || $destination == "东明库") {
			$storemanagedata = $model3->where('storename=\''.$storenameA.'\'')->getByProduct ( $product );
			if (! $storemanagedata) {
				$model2->rollback();
				$this->ajaxReturn ( '0', '东明库列表不存在' . $product . '相关物品!', '300' );
			}
		}
	  //南曹库判断
		if ($customer == "南曹库" || $destination == "南曹库") {
			$storemanagedata = $model3->where('storename=\''.$storenameB.'\'')->getByProduct ( $product );
			if (! $storemanagedata) {
				$model2->rollback();
				$this->ajaxReturn ( '0', '南曹库列表不存在' . $product . '相关物品!', '300' );
			}
		}
		
		//金海库判断
		if ($customer == "金海库" || $destination == "金海库") {
			$storemanagedata = $model3->where('storename=\''.$storenameC.'\'')->getByProduct ( $product );
			if (! $storemanagedata) {
				$model2->rollback();
				$this->ajaxReturn ( '0', '金海库列表不存在' . $product . '相关物品!', '300' );
			}
		}
		$data4['id']=$_REQUEST['id'];
		$data4['sweight']=$_REQUEST['sweight'];//皮重
		$data4['eweight']=$_REQUEST['eweight'];//毛重
		$data4['Factorynetweight']=$sweight;//出厂净重
		$data4['carstat']=$_REQUEST['carstat'];
		$result4=$model4->save ($data4);
		//更新拟定调度表信息
		$result3 = $model2->where('id='.$ControlTable['contractlogid'])->save($datactlog); 
		$result2 = $model2->where('id='.$ControlTable['tocontractlogid'])->save($todatactlog);
		//写入调度信息
		$n=$_SESSION['loginUserName'] ;//当前操作人	
		$data['control']=$_REQUEST['id'];//对应的调度信息ID
		$data['logtime']=date('YmdHis');//用于调度进度显示的时间
		$data['log']='订单号为：'.$orders.'被'.$n.'录入吨数，毛重：'.$_REQUEST['eweight'].'皮重：'.$_REQUEST['sweight'];//用于调度进度显示的记录
		$result5=$model5->add($data);
		if (($result2!==false)&&($result!==false) && ($result1!==false)&&($result4!==false) && ($result5!==false)&&($result3!==false)&&(RSMDM!==false)&&($RSMJH!==false)&&($RSMNC!==false)) {
			$model2->commit (); // 提交事务
			$this->ajaxReturn ( 1,'信息添加成功！', 200 );
		} else {
			$model2->rollback ();
			$this->ajaxReturn ( 0, '操作出错请联系管理员!', 300 );
		}
	}
	}
	/**
	 * 客户是否修改
	 */
	public function cusupdate($_REQUEST) {
		$ctlog = M('ContractLog');
		$id = $_REQUEST ['id'];
		$product = $_REQUEST['product'];
		$model1 = M ( 'ControlTable' );
		$model5 = M ( "StoreManage" );
		$sweight = bcsub($_REQUEST ['eweight'],$_REQUEST ['sweight'],4); // 出厂净重=毛重-皮重
		$Con = $model1->where ( 'id=' . $id )->find ();
		$SecidAndConLogid = explode('s', $_REQUEST['customer']);
		//计算差值
		$Dvalue = bcsub($sweight,$Con ['Factorynetweight'],4);
		if($_REQUEST['customer']!==""){
		    $cusid = $SecidAndConLogid[1];
		    $ContractLogid = $SecidAndConLogid[0];
		    $_POST['customer']=$cusid;
		    $_POST['contractlogid']=$ContractLogid;
		}else{
			$cusid = $Con['customer'];
			$ContractLogid = $Con['contractlogid'];
			$_POST['customer']=$cusid;
			$_POST['contractlogid']=$ContractLogid;
		}
		//如果客户无更改
		if($Con['customer']==$cusid){
			//如果客户为仓库
			if($cusid=="1"){
				$Astoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\'storeA\'' )->select ();
				if(count($Astoremanage)==0){
					$this->ajaxReturn(0,"东明库不存在".$product,300);
				}
				$datage ['stock'] = bcadd($Astoremanage [0] ['stock'],$Dvalue,4);
				$model5->where ( 'product=\'' . $product . '\' and storename=\'storeA\'' )->save($datage);
			}else{
				if($cusid=="2"){
					$Bstoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\'storeB\'' )->select ();
					if(count($Bstoremanage)==0){
						$this->ajaxReturn(0,"南曹库不存在".$product,300);
					}
					$datage ['stock'] = bcadd($Bstoremanage [0] ['stock'],$Dvalue,4);
					$model5->where ( 'product=\'' . $product . '\' and storename=\'storeB\'' )->save($datage);
				}else{
					if($cusid=="3"){
						$Cstoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\'storeC\'' )->select ();
						if(count($Cstoremanage)==0){
							$this->ajaxReturn(0,"金海库不存在".$product,300);
						}
						$datage ['stock'] = bcadd($Bstoremanage [0] ['stock'],$Dvalue,4);
						$model5->where ( 'product=\'' . $product . '\' and storename=\'storeC\'' )->save($datage);
					}else{
						//如果不为仓库
						$ctloglist = $ctlog->find($ContractLogid);
						$ctlogdate['alshipment'] = bcadd($Dvalue,$ctloglist['alshipment'],4);
 						$ctlogdate['status'] = ($ctlogdate['alshipment']/$ctloglist['capacity'])*100;
 						$ctlog->where('id='.$ContractLogid)->save($ctlogdate);
					}
				}
			}
		}else{
			//否则客户更改 先 计算新客户的量后还原之前的客户量
			if($cusid=="1"){
				$datage ['stock'] = $sweight;
			    $Astoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\'storeA\'' )->select ();
				if(count($Astoremanage)==0){
					$this->ajaxReturn(0,"东明库不存在".$product,300);
				}
				$model5->where ( 'product=\'' . $product . '\' and storename=\'storeA\'' )->save($datage);
			}else{
				if($cusid=="2"){
					$datage ['stock'] = $sweight;
					$Bstoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\'storeB\'' )->select ();
					if(count($Bstoremanage)==0){
						$this->ajaxReturn(0,"南曹库不存在".$product,300);
					}
					$model5->where ( 'product=\'' . $product . '\' and storename=\'storeB\'' )->save($datage);
				}else{
					if($cusid=="3"){
						$datage ['stock'] = $sweight;
						$Cstoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\'storeC\'' )->select ();
						if(count($Cstoremanage)==0){
							$this->ajaxReturn(0,"金海库不存在".$product,300);
						}
						$model5->where ( 'product=\'' . $product . '\' and storename=\'storeC\'' )->save($datage);
					}else{
						//如果不为仓库
						$ctloglist = $ctlog->find($ContractLogid);
						$ctlogdate['alshipment'] = bcadd($sweight,$ctloglist['alshipment'],4);
						$ctlogdate['status'] = ($ctlogdate['alshipment']/$ctloglist['capacity'])*100;
						$ctlog->where('id='.$ContractLogid)->save($ctlogdate);
					}
				}
			}
			//还原老客户的拟定调度信息
			if($Con['customer']=="1"){
				$Astoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\'storeA\'' )->select ();
				$datage ['stock'] = bcsub($Astoremanage [0] ['stock'],$sweight,4);
				$model5->where ( 'product=\'' . $product . '\' and storename=\'storeA\'' )->save($datage);
			}else{
				if($Con['customer']=="2"){
					$Bstoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\'storeB\'' )->select ();
				    $datage ['stock'] = bcsub($Bstoremanage [0] ['stock'],$sweight,4);
					$model5->where ( 'product=\'' . $product . '\' and storename=\'storeB\'' )->save($datage);
				}else{
					if($Con['customer']=="3"){
						$Cstoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\'storeC\'' )->select ();
				        $datage ['stock'] = bcsub($Cstoremanage [0] ['stock'],$sweight,4);
						$model5->where ( 'product=\'' . $product . '\' and storename=\'storeC\'' )->save($datage);
					}else{
						//如果不为仓库
						$ctloglist = $ctlog->find($Con['contractlogid']);
						$ctlogdate['alshipment'] = bcsub($ctloglist['alshipment'],$Con ['Factorynetweight'],4);
						$ctlogdate['status'] = ($ctlogdate['alshipment']/$ctloglist['capacity'])*100;
						$ctlog->where('id='.$Con['contractlogid'])->save($ctlogdate);
					}
				}
			}
		}
		//修改拟定调度信息
		if($Dvalue!==0){
			$ctloglist = $ctlog->find($Con['tocontractlogid']);
			$ctlogdate['alshipment'] = bcadd($ctloglist['alshipment'],$Dvalue,4);
			$ctlogdate['status'] = ($ctlogdate['alshipment']/$ctloglist['capacity'])*100;
			$ctlog->where('id='.$Con['tocontractlogid'])->save($ctlogdate);
		}
	}
	/**
	 * 客户是否修改
	 */
	public function editCarrierDispatch($_REQUEST) {
		$model1 = M ( 'ControlTable' );
		$model3 = M ( 'CarrierDispatch' );
		$id = $_REQUEST ['id'];
		$Con = $model1->where ( 'id=' . $id )->find ();
		
		$SecidAndConLogid = explode('s', $_REQUEST['customer']);
		if($_REQUEST['customer']!==""){
			$cusid = $SecidAndConLogid[1];
		}else{
			$cusid = $Con['customer'];
		}
		
		$orders=$Con['orders'];
		//起始地
		$start=$_REQUEST['start'];
		//目的地
		$destination = $_REQUEST['destination'];
		//客户
	    $customer = $cusid;
		//供应商
		$providerid = $Con['provider'];
		//承运方
		$carrier = $Con['carrier'];
		// 发货方
		$shipper = $Con['shipper'];
		// 车牌号
		$carno = $Con['carno'];
		$sweight = bcsub($_REQUEST ['eweight'],$_REQUEST ['sweight'],4); // 出厂净重=毛重-皮重
		//更新租车信息
		$list3 = $model3->where ( 'orders=' . $orders )->select();
		if(count($list3)>0){
			//租车信息修改存入map中
			$map ['customer'] = $customer;
			$map ['cweight'] = $sweight;//出厂净重
			$map ['status'] = 0;
			$map ['beginning'] = $start;
			$map ['destination'] = $destination;
			$RCD = $model3->where ( 'orders=' . $orders )->save ( $map );
		}else{
			$map ['carrierid'] = $carrier;
			$map ['sendername'] = $shipper;
			$map ['customer'] = $customer;
			$map ['providername'] = $providerid;
			$map ['carno'] = $carno;
			$map ['beginning'] = $start;
			$map ['destination'] = $destination;
			$map ['cweight'] = $sweight;
			$map ['status'] = 0;
			$map ['orders'] = $orders;
			$RCD = $model3->add ( $map );
		}
		return $RCD;
	}
	public function _before_update() {
		$ctlog = M('ContractLog');
		$type = $_REQUEST ['type'];
		$id = $_REQUEST ['id'];
		$model = M ( 'Provider' );
		$model1 = M ( 'ControlTable' );
		$model1->startTrans();//开启事务
		$model2 = M ( 'Freight' );
		$model3 = M ( 'CarrierDispatch' );
		$model4 = M ( 'Unload' );
		$model5 = M ( "StoreManage" );
		$result3 = true;
		$RCD = true;
		$RDM = true;
		$RNC = true;
		$RJH = true;
		$RP = true;
		$sweight = bcsub($_REQUEST ['eweight'],$_REQUEST ['sweight'],4); // 出厂净重=毛重-皮重
		$Con = $model1->where ( 'id=' . $id )->find ();
		//判断客户是否更改
		$cusid = $this->cusupdate($_REQUEST);
		//判断供应商
		$RCD = $this->editCarrierDispatch($_REQUEST);
		$orders=$Con['orders'];
		//起始地
		$start=$_REQUEST['start'];
		//目的地
		$destination = $_REQUEST['destination'];
		//供应商
		$providerid = $Con['provider'];
		//承运方
		$carrier = $Con['carrier'];
		// 发货方
		$shipper = $Con['shipper']; 
		// 车牌号
		$carno = $Con['carno']; 
	//	$sweight = bcsub($_REQUEST ['eweight'],$_REQUEST ['sweight'],4); // 出厂净重=毛重-皮重
		//按照修改的毛重与皮重，计算修改后的出厂净重
		$_POST['Factorynetweight']=$sweight;
		// 修改后出厂净重差值
		$Difference = bcsub($Con['Factorynetweight'],$sweight,4);
		
		//租车信息修改存入map中
		$map ['cweight'] = $sweight;//出厂净重
		$map ['status'] = 0;
		$map ['beginning'] = $start;
		$map ['destination'] = $destination;
		//查看是否已经有订单号的卸车和承运商结算记录
		//$status = $model3->where ( 'orders=' . $orders )->getField ( 'status' );
		$Unloaddata = $model4->getByOrders ( $orders);
			$provider = $model->where('id='.$providerid)->find();
			//客户
			$customer = $Con['customer'];
			/*
			if($provider['providername']=='东明库'){
				if($start!=='东明库'){
					$model1->rollback();
					$this->ajaxReturn(0,'供应商为东明库时起始地只能为东明库！',300);
				}
			}
			if($provider['providername']=='南曹库'){
				if($start!=='南曹库'){
					$model1->rollback();
					$this->ajaxReturn(0,'供应商为南曹库时起始地只能为南曹库！',300);
				}
			}
			if($provider['providername']=='金海库'){
				if($start!=='金海库'){
					$model1->rollback();
					$this->ajaxReturn(0,'供应商为金海库时起始地只能为金海库！',300);
				}
			}
			if($customer=='东明库'){
				if($destination!=='东明库'){
					$model1->rollback();
					$this->ajaxReturn(0,'供应商为东明库时起始地只能为东明库！',300);
				}
			}
			if($customer=='南曹库'){
				if($destination!=='南曹库'){
					$model1->rollback();
					$this->ajaxReturn(0,'供应商为南曹库时起始地只能为南曹库！',300);
				}
			}
			if($customer=='金海库'){
				if($destination!=='金海库'){
					$model1->rollback();
					$this->ajaxReturn(0,'供应商为金海库时起始地只能为金海库！',300);
				}
			}*/
			
			//处理供应商
		if (! $Unloaddata) {
			$storenameA='storeA';
			$storenameB='storeB';
			$storenameC='storeC';
			$product=$Con['product'];
			$Provider = $model->where ( 'id=\'' . $Con ['provider'] . '\'' )->find ();
			
			if ($Provider['providername']=="东明库"){
				$Astoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->select ();
				if ($Astoremanage) {
					$datage ['stock'] = bcadd($Astoremanage [0]['stock'],$Difference,4);
					if ($datage ['stock'] < 0) {
						$model1->rollback();
						$this->ajaxReturn ( 0, '东明库存不足！', 300 );
					}else{
						$RDM =  $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameA.'\'' )->save($datage);
					}
				} else {
					$model1->rollback();
					$this->ajaxReturn ( '0', '东明库列表不存在' . $product . '相关物品!', '300' );
				}
			}
			else{
				if($Provider['providername']=="南曹库"){
					$Astoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->select ();
					if ($Astoremanage) {
						$datage ['stock'] = $Astoremanage [0]['stock']+$Difference;
						if ($datage ['stock'] < 0) {
							$model1->rollback();
							$this->ajaxReturn ( 0, '南曹库存不足！', 300 );
						}else{
							$RNC = $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameB.'\'' )->save($datage);
						}
					} else {
						$model1->rollback();
						$this->ajaxReturn ( '0', '南曹库列表不存在' . $product . '相关物品!', '300' );
					}
				}else{
					if($Provider['providername']=="金海库"){
						$Astoremanage = $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->select ();
						if ($Astoremanage) {
							$datage ['stock'] = $Astoremanage [0]['stock']+$Difference;
							if ($datage ['stock'] < 0) {
								$model1->rollback();
								$this->ajaxReturn ( 0, '金海库存不足！', 300 );
							}else{
								$RJH = $model5->where ( 'product=\'' . $product . '\' and storename=\''.$storenameC.'\'' )->save($datage);
							}
						} else {
							$model1->rollback();
							$this->ajaxReturn ( '0', '金海库列表不存在' . $product . '相关物品!', '300' );
						}
					}else{
						if ($Con['shipper'] == "普天") {
							$data ['wshipment1'] = $Provider ['wshipment1'] + $Difference;
							$i = 1;
						} else {
							if ($Con['shipper'] == "兰亭") {
								$data ['wshipment2'] = $Provider ['wshipment2'] + $Difference;
								$i = 2;
							} else {
								if ($Con['shipper'] == "天地") {
									$data ['wshipment3'] = $Provider ['wshipment3'] + $Difference;
									$i = 3;
								}
							}
						}
						if ($data ['wshipment' . $i] < 0) {
							$model1->rollback();
							$this->ajaxReturn ( '0', "供应商无足够货物可用", '300' );
						} else {
							//更新供应商吨数信息
							$RP = $model->where ( 'id=\'' . $Con['provider'] . '\'' )->save ( $data );
						}
					}
				}
			}	
		}else {
// 			if ('1' == $status) {
// 				$model1->rollback();
// 			    $this->ajaxReturn ( '0', "相关租车信息已经付过款，不能修改调度信息！", '300' );
// 			} else {
			if ($Unloaddata){
				$model1->rollback();
		        $this->ajaxReturn ( '0', "相关调度信息已经卸过车，不能修改调度信息！", '300' );
			}
// 			}
		}
		
		//写入调度信息
		$model6=M('ControlLog');
		$n=$_SESSION['loginUserName'] ;//当前操作人
		$data['control']=$_REQUEST['id'];//对应的调度信息ID
		$data['logtime']=date('YmdHis');//用于调度进度显示的时间
		$data['log']='修改调度，订单号为：'.$orders.'被'.$n.'录入吨数，毛重：'.$_REQUEST['eweight'].'皮重：'.$_REQUEST['sweight'];//用于调度进度显示的记录
		$result5=$model6->add($data);
		if(($result5!==false)&&($RCD!==false)&&($RDM!==false)&&($result3!==false)&&($RJH!==false)&&($RNC!==false)&&($RP!==false)){
			$model1->commit();
		}else{
			$model1->rollback();
			$this->ajaxReturn(0,"修改失败，请联系管理员",300);
		}
	}

	/**
	 * 接受页面传来的参数调用删除功能
	 */
	public function _before_foreverdelete() {
		$id = $_REQUEST ['ids'];
		$CT = M ( 'ControlTable' );
		$CT->startTrans();
		$RCL = $this->UpwardReductionContractLog($id);
		$Rcondelete =  $this->controdelete($id);
		if(($RCL!==false)&&($Rcondelete!==false)){
			$CT->commit();
		}else{
			$CT->rollback();
			$this->ajaxReturn(0,"删除失败,请联系管理员",300);
		}
	}
	/**
	 * 调度的删除功能
	 * @param $id
	 */
	public function controdelete($id){
		$model1 = M ( 'ControlTable' );
		$model2 = M ( 'CarrierDispatch' );
		//事务交上级处理
		//$model2->startTrans (); // 开启事务
		$model3 = M ( 'Unload' );
		$model4 = M ( "StoreManage" );
		$model5 = M('ContractLog');
		$result=true;
		$result1 = true;
		$result2 = true;
		$result3 = true;
		$result5 = true;
		if(is_array($id)){
			$condition = $id;
			
		}else{
			$condition = explode ( ',', $id );
		}
		$k = count ( $condition );
		for($j = 0; $j < $k; $j ++) {
			$ControlTable = $model1->where ( 'id=' . $condition [$j] )->find ();
			$shipper = $ControlTable ['shipper'];
			$start = $ControlTable['start'];//起运地
			$product = $ControlTable['product']; // 产品名称
			$sweight = $ControlTable['Factorynetweight'];//出厂净重
			$tocontractlogid = $ControlTable['tocontractlogid'];
			// 还原供货商的剩余量
			$model = M ( 'Provider' );
			$Provider = $model->field ( 'id,providername,wshipment1,wshipment2,wshipment3' )->where ( 'id=\'' . $ControlTable ['provider'] . '\'' )->find ();
			//当供应商为仓库时
			//当供应商或者起运地为仓库时还原仓库吨数
			if(($Provider['providername']=="东明库")||($start=='东明库')){
				$smdata = $model4->getByProduct ( $product );
				$storename='storeA';
				if ($smdata) {
					$Astoremanage = $model4->where ( 'product=\'' . $product . '\' and storename=\''.$storename.'\'' )->select ();
					$datage ['stock'] = bcadd($Astoremanage [0] ['stock'],$sweight,4);
				} else {
					$this->ajaxReturn ( '0', '东明库列表不存在' . $product . '相关物品!', '300' );
				}
			}else{
				if(($Provider['providername']=="南曹库")||($start=='南曹库')){
					$smdata = $model4->getByProduct ( $product );
					$storename='storeB';
					if ($smdata) {
						$Astoremanage = $model4->where ( 'product=\'' . $product . '\' and storename=\''.$storename.'\'' )->select ();
						$datage ['stock'] = bcadd($Astoremanage [0] ['stock'],$sweight,4);
					} else {
						$this->ajaxReturn ( '0', '南曹库列表不存在' . $product . '相关物品!', '300' );
					}
				}else{
					if(($Provider['providername']=="金海库")||($start=='金海库')){
						$smdata = $model4->getByProduct ( $product );
						$storename='storeC';
						if ($smdata) {
							$Astoremanage = $model4->where ( 'product=\'' . $product . '\' and storename=\''.$storename.'\'' )->select ();
							$datage ['stock'] = bcadd($Astoremanage [0] ['stock'],$sweight,4);
						} else {
							$this->ajaxReturn ( '0', '南曹库列表不存在' . $product . '相关物品!', '300' );
						}
					}else{
						if ($shipper == "普天") {
							$data ['wshipment1'] = $Provider ['wshipment1'] + bcsub($ControlTable ['eweight'],$ControlTable ['sweight'],4);
							$i = 1;
						} else {
							if ($shipper == "兰亭") {
								$data ['wshipment2'] = $Provider ['wshipment2'] + bcsub($ControlTable ['eweight'],$ControlTable ['sweight'],4);
								$i = 2;
							} else {
								if ($shipper == "天地") {
									$data ['wshipment3'] = $Provider ['wshipment3'] + bcsub($ControlTable ['eweight'],$ControlTable ['sweight'],4);
									$i = 3;
								}
							}
						}
					}
				}
			}
			$status = $model2->where ( 'orders=' . $ControlTable ['orders'] )->getField ( 'status' );
			$Unloaddata = $model3->getByOrders ( $ControlTable ['orders'] );
			// 删除对应的租车信息，当租车信息付过款式不能删除,除非用户为admin
			if ((! $Unloaddata && ('0' == $status))||('1'==$_SESSION [C ( 'USER_AUTH_KEY' )])) {
				if($data){
					$result1 = $model->where ( 'id=\'' . $ControlTable ['provider'] . '\'' )->save ( $data );
				//修改供应商拟定调度信息
					
					$list5 = $model5->find($tocontractlogid);
					$data5['alshipment'] = bcsub($list5['alshipment'],$ControlTable['Factorynetweight'],4);
					$data5['status']  = ($data5['alshipment']/$list5['capacity'])*100;
					$result5 = $model5->where('id='.$tocontractlogid)->save($data5);
				}
				if($datage){
					$result2 = $model4->where ( 'product=\'' . $product . '\' and storename=\''.$storename.'\'' )->save($datage);
				}
				$result = $model2->where ( 'orders=' . $ControlTable ['orders'] )->delete ();
				//删除卸车记录
				$result3 = $model3->where ( 'orders=' . $ControlTable ['orders'] )->delete ();
				//$model->commit (); // 提交事务
			} else {
				if ('1' == $status) {
					$this->ajaxReturn ( '0', "相关租车信息已经付过款，不能删除调度信息！", '300' );
				} else {
					if ($Unloaddata){
						$this->ajaxReturn ( '0', "相关调度信息已经卸过车，不能删除调度信息！", '300' );
				
					}
				}
			}
		}
		if(($result!==false)&&($result1!==false)&&($result2!==false)&&($result5!==false)){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 如果已经装车（录入吨数）删除调度操作之后向上还原拟定调度的已调度数
	 * 需要传递上级的ID[]
	 * @param $id 调度表的ID 
	 */
    public function UpwardReductionContractLog($id){
    	$model1 = M('ContractLog');
    	$model2 = M ( 'ControlTable' );
    	$ControlTableid = explode ( ',', $id );
		$k = count ( $ControlTableid );
		$RCL = true;
		for($j = 0; $j < $k; $j ++) {
			$ControlTable = $model2->where ( 'id=' . $ControlTableid [$j] )->find ();
			//需要还原的吨数
			$tunnage = $ControlTable['Factorynetweight'];
			//上级拟定调度表的ID
			$contractlogid = $ControlTable['contractlogid'];
			if($contractlogid){
				$ContractLog = $model1->find($contractlogid);
				//拟定调度表可调度吨数
				$capacity = $ContractLog['capacity'];
				//拟定调度表已调度吨数
				$alshipment = $ContractLog['alshipment'];
				//收集信息
				$datactlog['alshipment']=bcsub($alshipment, $tunnage,4);//删除后调度的表已调度数增加
				$datactlog['status'] = ($datactlog['alshipment']/$capacity)*100;
				$RCL = $model1->where('id='.$contractlogid)->save($datactlog);
				if($RCL == false){
					return $RCL;
				}
			}
		}
		return $RCL;
}
	//高级检索
	public function retrieval(){
	    $model4 = M ( "Customer" );
	    $model3 = M ( "provider" );
	    $model2 = M("Freight");
		$Customer = $model4->where('removed=1')->select ();
		$Provider = $model3->select ();
		$freight = $model2->distinct ( true )->field ( 'startaddress' )->select ();
		$end = $model2->distinct ( true )->field ( 'endaddress' )->select ();
	    $this->getSubCompany ();
	    $this->getGoods ();
	    $this->assign ( 'list4', $Customer );
	    $this->assign ( 'list3', $Provider );
	    $this->assign('end',$end);
	    $this->assign('freight',$freight);
		//$this->assign('user',$user);
		$this->display();
	}
	//在计算总额之前，查找出客户、供应商、承运商信息，以便能根据id显示出名字
	public function _before_priceentrypay(){
		$model1=D("Customer");
		$customer=$model1->select();
		$model2=D("Provider");
		$provider=$model2->select();
		$model3=D("Carrier");
		$carrier=$model3->select();
		$this->assign("cus",$customer);
		$this->assign("pro",$provider);
		$this->assign("carrier",$carrier);		
	}
	// 根据时间段，查询符合条件的调度记录信息，计算总额
	public function priceentrypay() {
		$start=$_POST ['start'];
		$end=$_POST ['end'];
		$startaddress = $_POST['startaddress'];
		$endaddress = $_POST['destination'];
		$shipper=$_POST ['shipper'];
		$carno = $_POST['carno'];
		$orders=$_POST['orders'];
		//$customer=$_POST ['customer'];
		$cust="".$_POST ['customer'];//得到输入的客户名称
		$providerid=$_POST ['provider'];
		$providerModel=M("Provider");
		$provider=$providerModel->getByProvidername($providerid);
		$customerModel=M("Customer");
		$customer=$customerModel->getByCustomername($cust);//查找该客户名称的信息，得到客户id
		$carstat=$_POST ['carstat'];
		$product=$_POST ['product'];
		$zjz=0;//总出厂净重
		$xhzjz=0;//总卸货净重
		if(!empty($shipper)){
			$map['shipper'] = array('eq',$shipper);
		}
		if(!empty($cust)){
			$map['customer'] = array('eq',$customer['id']);
		}
		if(!empty($carstat)){
			$map['carstat'] = array('eq',$carstat);
		}
		if(!empty($product)){
			$map['product'] = array('eq',$product);
		}
		if(!empty($provider)){
			$map['provider'] = array('eq',$provider['id']);
		}
		if(!empty($startaddress)){
            $map['start'] = array('eq',$startaddress);
		}
		if(!empty($endaddress)){
			$map['destination'] = array('eq',$endaddress);
		}
		if(!empty($carno)){
			$map['carno'] = array('eq',$carno);
		}
		if(!empty($orders))
		{
			$map['orders'] = array('eq',$orders);
		}
// 		if(!empty($start)){
// 			$map['controldate']=array('egt',$start);
// 		}
// 		if(!empty($end)){
// 			$map['controldate']=array('elt',$end.' 23:59:59');
// 		}
	   if(!empty($start)&&(!empty($end))){
			$map['controldate'] = array('between',array($start.' 00:00:00',$end.' 23:59:59'));
		}else{
			if(!empty($start)){
				$map['controldate']=array('egt',$start);
			}else{
				if(!empty($end)){
					$map['controldate']=array('elt',$end.' 23:59:59');
				}
			}
		}
		$map['removed']=1;
		$model=M('ControlTable');
		
		$ControlTable=$model->where($map)->order('controldate desc')->select();
		if($ControlTable){
			for($i=0;$i<count($ControlTable);$i++){
				if(null!==($ControlTable[$i]['Factorynetweight'])){
					$zjz+=$ControlTable[$i]['Factorynetweight'];
				}
				if(null!==($ControlTable[$i]['NetLandedWeight'])){
					$xhzjz+=$ControlTable[$i]['NetLandedWeight'];
				}
			}
		}

		$this->assign('start',$start);
		$this->assign('end',$end);
		$this->assign('shipper',$shipper);
		$this->assign('customer',$customer['id']);
		$this->assign('carstat',$carstat);
		$this->assign('product',$product);
		$this->assign('provider',$provider['id']);
		$this->assign('startaddress',$startaddress);
		$this->assign('destination',$endaddress);
		$this->assign('carno',$carno);
		$this->assign('orders',$orders);
		$this->assign('list',$ControlTable);
		$this->assign ( 'zjz', $zjz );//总出厂净重
		$this->assign ( 'count', count ( $ControlTable ));
		$this->assign ( 'xhzjz', $xhzjz );//总卸货净重
		
		
		
		$this->display();
	}
	//导出功能
	public function export(){
	
		$model=D('ControlTable');
		$shipper = $_GET['shipper'];
		$start = $_GET['start'];
		$end = $_GET['end'];
		$startaddress = $_GET['startaddress'];
		$endaddress = $_GET['destination'];
		$carno = $_GET['carno'];
		$customer = $_GET['customer'];
		$carstat = $_GET['carstat'];
		$product = $_GET['product'];
		$provider = $_GET['provider'];
		$orders = $_GET['orders'];
		$sql='select orders,shipper,ifnull(customername,"") customername,ifnull(providername,"") providername,start,destination,ifnull(carriername,"") carriername,carno, case carstat when 2 then "待发货" when 1 then "运送完毕"  when 3 then "已发货" when 0 then "请选择" end as carstat ,product,eweight,sweight,Factorynetweight,NetLandedWeight,loss,controldate,userid,note from mlt_control_table b  left join mlt_provider p on b.provider=p.id left join mlt_carrier c on b.carrier=c.id left join  mlt_customer cc on b.customer=cc.id  where 1=1 ';
		 if(!empty($shipper)){
			$sql.=' and b.shipper=\''.$shipper.'\'';
		}
		if(!empty($start)){
			$sql.=' and b.controldate >= \''.$start.'\'';
		}
		if(!empty($end))
		{
			$sql.=' and b.controldate <= \''.$end.' 23:59:59'.'\'';
		}
		if(!empty($customer)){
			$sql.=' and b.customer=\''.$customer.'\'';
		}
		if(!empty($carstat)){
			$sql.=' and b.carstat=\''.$carstat.'\'';
		}
		if(!empty($product)){
			$sql.=' and b.product=\''.$product.'\'';
		} 
		if(!empty($provider)){
			$sql.=' and b.provider=\''.$provider.'\'';
		}
		if(!empty($startaddress)){
			$sql.=' and b.start=\''.$startaddress.'\'';
		}
		if(!empty($endaddress)){
			$sql.=' and b.destination=\''.$endaddress.'\'';
		}
		if(!empty($carno)){
			$sql.=' and b.carno=\''.$carno.'\'';
		}
		if(!empty($orders)){
			$sql.=' and b.orders=\''.$orders.'\'';
		}
		$sql.=' and b.removed!= 2 order by controldate desc';
		$ControlTable=$model->query($sql);
		$cname=date('Y-m-d');
		 
		$map = array('订单号','发货方','客户','供应商','起运地','目的地','承运方','车牌号','车辆状态','产品名称','毛重(吨)','皮重(吨)','出厂净重','卸货净重','盈亏','调度时间','接车人','备注');
		$field=array('orders','shipper','customername','providername','start','destination','carriername','carno','carstat','product','eweight','sweight','Factorynetweight','NetLandedWeight','loss','controldate','userid','note');
		 
		$this->phpexcel($ControlTable, $cname, $map,$field);
		 
	}
	//调度进度
	public function  progress()
	{
		$id=$_REQUEST['id'];
		$model=M('ControlLog');
		$controllog=$model->where('control='.$id)->select();
		$this->assign('list',$controllog);
		$this->display();
	}
	 //允许卸货
	public function unload(){
		$id = $_REQUEST ['ids'];
		$model=M('ControlTable');
		$data['payondelivery']='0';
		if (isset ( $id )) {
			$condition = array (id => array ('in', explode ( ',', $id ) ) );
			if($model->where($condition)->getField('payondelivery')=='0'){
				$this->ajaxReturn ( 0, '已允许过!', 300 );
			}else{
			if (false !== $model->where ( $condition )->save($data)) {
				$this->ajaxReturn (1,'允许成功!',200);
			} else {
				$this->ajaxReturn (1,'允许失败!',300);
			}
			}
		} else {
				$this->ajaxReturn (1,'操作出现非法操作!',200);
		} 
 	}
 	public function _before_trash() {
 		$model = M ( "ControlTable" );
 		$list = $model->select ();
 		$model3 = M ( "Carrier" );
 		$Carrier = $model3->select ();
 		$model2 = M ( "Provider" );
 		$Provider=$model2->select ();
 		$model4 = M ( "Customer" );
 		$Customer=$model4->select ();
 		$this->assign ( 'carr', $Carrier );
 		$this->assign ( 'provider', $Provider );
 		$this->assign ( 'groupList', $list );
 		$this->assign ( 'customer', $Customer );
 	}
 	//判断是否为款到卸车
 	public function customerajax(){
 		$arr = $_POST;
        $model = M('Customer');
        $map['status']='';
        $map['cusproduct']='';
        $customer = $model->where('id='.$arr['customer'])->find();
        $payondelivery = $customer['payondelivery'];
        if($arr['customer']=="1"||$arr['customer']=="2"||$arr['customer']=="3"){
        	$this->ajaxReturn('',200,300);
        }else{
        	if($payondelivery){
        	$this->ajaxReturn("<span style='color:red;'>注意：本客户为款到卸车!</span>",200,200);
        	}else{
        			$this->ajaxReturn('',200,300);
        	}
        	
        }
 	}
 	
 	public function addnote()
 	{
 		if("true"==$_REQUEST['insertNote']){
 			$this->insertNote();
 		}else{
 		$id = $_REQUEST['id'];
 		$this->assign('id',$id);
 		$cg = M('ControlTable');
 		$list=$cg->where('id='.$id)->getField('note');
 		$this->assign('id',$id);
 		$this->assign('note',$list);
 		$this->display();
 		}
 	}
 	
 	public function insertNote()
 	{
 		$cg = M('ControlTable');
 		$id = $_REQUEST['id'];
 		$note=$_REQUEST['note'];
 	
 		//$list=$cg->where('id='.$id)->getField('note');
 		$map['note']=$note;
 		$result = $cg->where('id='.$id)->save($map);
 		if($result){
 			$this->ajaxReturn ( $result, '添加备注成功！', 200 );
 		}else{
 			$this->ajaxReturn ( $result, '添加备注失败！', 300 );
 		}
 	}
 	/**
 	 * 拟定调度
 	 */
 	public function BlockOutcontrol() {
 		if("true"==$_REQUEST['add']){
 			$this->_before_add();
 			$this->add();
 		}else{
 			if("true"==$_REQUEST['insert']){
 				$this->_before_insert();
 				$this->insert();
 			}else {
 				$model=M('ContractLog');
 				$userid=$_SESSION [C ( 'USER_AUTH_KEY' )];
 				//if($userid=='1'){
 					$sql = "select * from mlt_contract_log conlog  where status!=100   and capacity!=0 order by capatime desc";
 				//}else{
 					//$sql = "select * from mlt_contract_log conlog  where status!=100 and conlog.id in(select distinct controllogid from mlt_controllog_user conuser where userid=".$userid.")  order by capatime desc";
 				//}
 				$result = $model->query($sql);
 				$this->assign('list',$result);
 				$this->display();
 			}
 		}
 	}
 	/**
 	 * 拟定调度的删除
 	 */
 	public function blockoutdelete(){
 		$ids = $_REQUEST['ids'];
 		$this->UpwardReductionCustomerPayment($ids);
 		$this->fordelete($ids);
 	}
 	/**
 	 * 删除拟定调度时向上还原拟定审批的已调度数
 	 * 
 	 */
 	public function UpwardReductionCustomerPayment($ids){
 		$model1 = M('CustomerPayment');
 		$model2 = M('ContractLog');
 		$ContractLogid = explode ( ',', $ids );
 		$k = count ( $ContractLogid );
 		for($j = 0; $j < $k; $j ++) {
 			$ContractLog = $model2->where ( 'id=' . $ContractLogid [$j] )->find ();
 		    //需要还原的已经审批吨数
 			$tunnage = $ContractLog['capacity'];
 			//上级拟定审批表的ID
 			$customerpaymentid = $ContractLog['customerpaymentid'];
 			$CustomerPayment = $model1->find($customerpaymentid);
 			//拟定审批表可审批吨数
 			$capacity = $CustomerPayment['capacity'];
 			//拟定审批表已审批吨数
 			$alshipment = $CustomerPayment['alshipment'];
 			//收集信息
 			$cpmap['alshipment']=bcsub($alshipment,$tunnage,4);//已审批数
 			$cpmap['status']=($cpmap['alshipment']/$capacity)*100;
 			$model1->where('id='.$customerpaymentid)->save($cpmap);
 		}
 	}
 	/**
 	 * 拟定调度的删除功能
 	 */
 	
 	public function fordelete($ids){
 		$model = M('ContractLog');
 		$model1 = M ( 'ControlTable' );
 		$model2 = M('ControllogUser');
 		$ContractLogid = explode ( ',', $ids );
 		$k = count ( $ContractLogid );
 		//删除本拟定调度生成的调度信息
 		for($j = 0; $j < $k; $j ++){
 				
 			$ControlTableid = $model1->field('id')->where('contractlogid='.$ContractLogid[$j])->select();
 			for($i=0;$i<count($ControlTableid);$i++){
  			$arr[$i] = $ControlTableid[$i]['id'];
 			}
 			if($arr){
 				$this->controdelete($arr);
 				$condition = array (id => array ('in', $arr) );
 				$model1->where ( $condition )->delete ();
 			}
 			//删除对应权限表
 			$model2->where('controllogid='.$ContractLogid [$j])->delete();
//  			$c = count ( $contractlogid );
//  			if(!empty($c)){
//  				for($i=0;$i<$c;$i++){
//  					$this->controdelete($contractlogid[$i]['contractlogid']);
//  				}
//  			}
           
 			//删除本拟定调度
 			$result = $model->where('id='.$ContractLogid[$j])->delete();
 			if(!$result){
 				$this->insertLog('彻底删除','操作删除拟定调度编号为'.$ContractLogid[$j].'的数据失败');
 				$this->ajaxReturn (1,'删除失败!',300);
 			}
 		}
 		
 		if ($result) {
 			$this->insertLog('彻底删除','操作删除拟定调度编号为'.$ContractLogid.'的数据成功');
 			$this->ajaxReturn (1,'删除成功!',200);
 		} 
 	}
}
